/*
 * Created on 2005-4-8
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package cn.com.yinhex.as.util;

import java.security.MessageDigest;


/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class EncryptUtil
{
	public static String getMD5(String str)
	{
		return encode(str, "MD5");
	}

	public static String getSHA1(String str)
	{
		return encode(str, "SHA-1");
	}

	public static String getLittleMD5(String str)
	{
		String estr = encode(str, "MD5");
		return estr.substring(0, 20);
	}

	public static String getLittleSHA1(String str)
	{
		String estr = encode(str, "SHA-1");
		return estr.substring(0, 20);
	}

	private static String encode(String str, String type)
	{
		try
		{
			MessageDigest alga = java.security.MessageDigest.getInstance(type);
			alga.update(str.getBytes("UTF-8"));
			byte[] digesta = alga.digest();
			return byte2hex(digesta);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return "";
		}
	}

	public static String uuid(String[] strs)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			for (int i = 0; i < strs.length; i++)
			{
				if (StringUtil.isFine(strs[i]))
				{
					md.update(strs[i].getBytes());
				}
			}
			byte[] bs = md.digest();
			return byte2hex(bs);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	public static String byte2hex(byte[] b)
	{
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++)
		{
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	public static byte[] hex2byte(byte[] b)
	{
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("���Ȳ���ż��");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2)
		{
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}
}
